import axios, { type Method } from 'axios'
import { showToast } from 'vant'

const baseURL = import.meta.env.VITE_BASE_URL
const instance = axios.create({ baseURL, timeout: 10000 })

instance.interceptors.request.use((config) => {
  return config
})

instance.interceptors.response.use(
  (res) => {
    if (res.status !== 200) {
      showToast(res.statusText || '网络异常')
    }

    const { code, data, msg } = res.data
    switch (code) {
      case 1:
        return data
      default:
        msg && ~showToast(msg) && Promise.reject()
    }
  },
  (err) => Promise.reject(err)
)

const request = <T>(url: string, method: Method = 'GET', data?: object) => {
  return instance.request<T, T>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: data,
  })
}

export { baseURL, instance }

export default request
